package service;

import java.sql.*;

public class UserService {

    public static Connection conn;

    private static String root_username;
    private static String root_password;

    public UserService() {
        root_username = "root";
        root_password = "your password"; // TODO: change it yourself
    }

    public void getConnection() {
        if (conn != null) {
            return;
        }
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/frontend_db?useSSL=false&serverTimezone=UTC",
                                               root_username, root_password);
            System.out.println("Database connect succedd!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public boolean userLogin(String username, String password) {
        String query = "SELECT COUNT(*) FROM users WHERE username = ? AND password = ?";
        try (PreparedStatement pstmt = conn.prepareStatement(query)) {
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                return rs.getInt(1) > 0;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean userRegist(String username, String password) {
        String checkUserSQL = "SELECT * FROM users WHERE username = ?";
        String insertUserSQL = "INSERT INTO users (username, password) VALUES (?, ?)";

        try {
            PreparedStatement checkStmt = conn.prepareStatement(checkUserSQL);
            checkStmt.setString(1, username);
            ResultSet rs = checkStmt.executeQuery();

            if (rs.next()) {
                return false;
            }
            PreparedStatement insertStmt = conn.prepareStatement(insertUserSQL);
            insertStmt.setString(1, username);
            insertStmt.setString(2, password);

            int rowsAffected = insertStmt.executeUpdate();
            return rowsAffected > 0;

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return true;
    }
};
